package com.sxsihe.heartmate.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.*;
import android.graphics.drawable.BitmapDrawable;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.View;

import com.sxsihe.heartmate.R;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ECGProgressView extends View {
    Paint mPaint = null;
    private int mWidth,mHeight,barHeight,bottomHeight;
    private float scaleplateTextSize,currentTextSize;
    int begin=0;
    int end=0;
    int current=0;
    String node = "";
    int bgColor,scaleplateTextColor,currentTextColor;
    Bitmap currentBitmap;
    int iconReference = 0;
    Bitmap bitmap;

    public void setCurrent(int current) {
        this.current = current;
        postInvalidate();
    }

    public ECGProgressView(Context context) {
        this(context, null);
    }

    public ECGProgressView(Context context, AttributeSet attrs) {
        this(context,attrs,0);
    }

    public ECGProgressView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.ECGProgressView);
        int n = array.getIndexCount();
        for (int i = 0; i < n; i++) {
            int attr = array.getIndex(i);
            switch (attr) {
                case R.styleable.ECGProgressView_begin:
                    begin = array.getInt(attr, 0);
                    break;
                case R.styleable.ECGProgressView_end:
                    end = array.getInt(attr, 100);
                    if(end<=begin){
                        end = begin+10;
                    }
                    break;
                case R.styleable.ECGProgressView_current:
                    current = array.getInt(attr, 50);
                    if(current>end||current<begin){
                        current = (end-begin)/2;
                    }
                    break;
                case R.styleable.ECGProgressView_node:
                    node = array.getString(attr);
                    break;
                case R.styleable.ECGProgressView_icon:
                    iconReference = array.getResourceId(attr, -1);
                    break;
                case R.styleable.ECGProgressView_bgColor:
                    bgColor = array.getColor(attr, Color.RED);
                    break;
                case R.styleable.ECGProgressView_scaleplateTextColor:
                    scaleplateTextColor = array.getColor(attr, Color.RED);
                    break;
                case R.styleable.ECGProgressView_currentTextColor:
                    currentTextColor = array.getColor(attr, Color.RED);
                    break;
                case R.styleable.ECGProgressView_scaleplateTextSize:
                    scaleplateTextSize = array.getDimensionPixelSize(attr, (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 16, getResources().getDisplayMetrics()));
                     break;
                case R.styleable.ECGProgressView_currentTextSize:
                    currentTextSize = array.getDimensionPixelSize(attr,(int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,16,getResources().getDisplayMetrics()));
                    break;
                case R.styleable.ECGProgressView_barHeight:
                    barHeight = array.getDimensionPixelSize(attr,(int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,16,getResources().getDisplayMetrics()));
                    break;
                case R.styleable.ECGProgressView_bottomHeight:
                    bottomHeight = array.getDimensionPixelSize(attr,(int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,16,getResources().getDisplayMetrics()));
                    break;
            }
        }
        array.recycle();
        bitmap = ((BitmapDrawable)getResources().getDrawable(iconReference)).getBitmap();
        mPaint = new Paint();
     }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        mPaint.setAntiAlias(true);
        currentBitmap =  ((BitmapDrawable)getResources().getDrawable(getResources().getIdentifier("toofast", "drawable", this.getContext().getClass().getPackage().getName()))).getBitmap();
        int rectLeft = currentBitmap.getWidth()/2;
        int rectRight = mWidth-currentBitmap.getWidth()/2;
        int rectWidth = rectRight - rectLeft;
        //最外层矩形
        mPaint.setColor(bgColor);
        int bitmapHeight = bitmap.getHeight();
        RectF rectBg = new RectF(rectLeft, bitmapHeight, rectRight, barHeight+bitmapHeight);
        canvas.drawRect(rectBg, mPaint);
        //内层多段矩形
        List<Map<String,String>> maps = new ArrayList<Map<String, String>>();

        String nodes [] = node.split("\\$");
        for(String n : nodes){
            String tmp[] = n.split(",");
            Map<String,String> map = new HashMap<String, String>();
            map.put("label",tmp[0]);
            map.put("icon",tmp[1]);
            map.put("color",tmp[2]);
            maps.add(map);
        }
//
        int scaleplateTextHeight=0;
        int i=0;
        for(Map<String,String> map : maps) {
            mPaint.setColor(Color.parseColor(map.get("color")));
            RectF rect;
            if(i==0) {
                rect = new RectF(rectLeft, bitmapHeight,  Float.parseFloat(map.get("label"))/(end-begin)*rectWidth+rectLeft, barHeight+bitmapHeight);
                if(current<Float.parseFloat(map.get("label"))){
                    currentBitmap = ((BitmapDrawable)getResources().getDrawable(getResources().getIdentifier(map.get("icon"), "drawable", this.getContext().getClass().getPackage().getName()))).getBitmap();
                }
            }else{
                rect = new RectF(
                        Float.parseFloat(maps.get(i - 1).get("label"))/(end-begin)*rectWidth+rectLeft,
                        bitmapHeight,
                        Float.parseFloat(map.get("label"))/(end-begin)*rectWidth+rectLeft,
                        barHeight+bitmapHeight
                );
                if(Float.parseFloat(maps.get(i-1).get("label"))<=current&&current<=Float.parseFloat(map.get("label"))){
                    currentBitmap = ((BitmapDrawable)getResources().getDrawable(getResources().getIdentifier(map.get("icon"), "drawable", this.getContext().getClass().getPackage().getName()))).getBitmap();
                }
            }
            canvas.drawRect(rect, mPaint);
//
            mPaint.setTextSize(scaleplateTextSize);
            Rect mBound = new Rect();
            mPaint.getTextBounds(map.get("label"), 0, map.get("label").length(), mBound);
            scaleplateTextHeight = barHeight+bitmapHeight+mBound.height()+10;
            mPaint.setColor(scaleplateTextColor);
            canvas.drawText(map.get("label"),
                    Float.parseFloat(map.get("label"))/(end-begin)*rectWidth-mBound.width()/2+rectLeft,
                    scaleplateTextHeight,
                    mPaint);
            i++;
        }
//
        mPaint.setTextSize(currentTextSize);
        Rect mBound = new Rect();
        mPaint.getTextBounds(String.valueOf(current), 0, String.valueOf(current).length(), mBound);
        mPaint.setColor(currentTextColor);
        canvas.drawText(String.valueOf(current),
                (rectWidth - mBound.width()) / 2+rectLeft,
                scaleplateTextHeight + mBound.height() + 20,
                mPaint);
//

        canvas.drawBitmap(currentBitmap,
                (float)current/(end-begin)*rectWidth-currentBitmap.getWidth()/2+rectLeft,
                0,
                mPaint);

        //得到当前值所占的比例
//        float section = currentCount/maxCount;
//        RectF rectProgressBg = new RectF(3, 3, (mWidth-3)*section, mHeight-3);
//        if(section <= 1.0f/3.0f){
//            if(section != 0.0f){
//                mPaint.setColor(SECTION_COLORS[0]);
//            }else{
//                mPaint.setColor(Color.TRANSPARENT);
//            }
//        }else{
//            int count = (section <= 1.0f/3.0f*2 ) ? 2 : 3;
//            int[] colors = new int[count];
//            System.arraycopy(SECTION_COLORS, 0, colors, 0, count);
//            float[] positions = new float[count];
//            if(count == 2){
//                positions[0] = 0.0f;
//                positions[1] = 1.0f-positions[0];
//            }else{
//                positions[0] = 0.0f;
//                positions[1] = (maxCount/3)/currentCount;
//                positions[2] = 1.0f-positions[0]*2;
//            }
//            positions[positions.length-1] = 1.0f;
//            LinearGradient shader = new LinearGradient(3, 3, (mWidth-3)*section, mHeight-3, colors,null, Shader.TileMode.MIRROR);
//            mPaint.setShader(shader);
//        }
//        canvas.drawRoundRect(rectProgressBg, round, round, mPaint);
//        canvas.drawBitmap(bitmap, (mWidth - 3) * section - bitmap.getWidth() / 2, mHeight, mPaint);

    }

    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec);
        int widthSpecSize = MeasureSpec.getSize(widthMeasureSpec);
        int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec);
        int heightSpecSize = MeasureSpec.getSize(heightMeasureSpec);
        if (widthSpecMode == MeasureSpec.EXACTLY ) {
            mWidth = widthSpecSize;
        } else {
            mWidth = 0;
        }
        if (heightSpecMode == MeasureSpec.AT_MOST || heightSpecMode == MeasureSpec.UNSPECIFIED) {
            Rect mBound = new Rect();
            mPaint.setTextSize(scaleplateTextSize);
            mPaint.getTextBounds("1", 0, 1, mBound);
            int textHeight = mBound.height();
            mPaint.setTextSize(currentTextSize);
            mPaint.getTextBounds("1", 0, 1, mBound);
            textHeight += mBound.height();
            mHeight = barHeight+textHeight+bitmap.getHeight()+bottomHeight+40;
        } else {
            mHeight = heightSpecSize;
        }
        setMeasuredDimension(mWidth, mHeight);
    }

    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        currentBitmap.recycle();
        currentBitmap = null;
        bitmap.recycle();
        bitmap = null;
        System.gc();
    }

    private int dipToPx(int dip) {
        float scale = getContext().getResources().getDisplayMetrics().density;
        return (int) (dip * scale + 0.5f * (dip >= 0 ? 1 : -1));
    }
}
